package com.hhq.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhq.system.common.model.Option;
import com.hhq.system.converter.TenantConverter;
import com.hhq.system.mapper.SysTenantMapper;
import com.hhq.system.model.entity.SysTenant;
import com.hhq.system.model.form.TenantForm;
import com.hhq.system.model.query.TenantPageQuery;
import com.hhq.system.model.vo.TenantPageVO;
import com.hhq.system.security.util.TenantContextHolder;
import com.hhq.system.service.SysTenantService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * <p>Description: some description </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/6/26 17:46
 */
@Service
@RequiredArgsConstructor
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements SysTenantService {

    private final TenantConverter tenantConverter;

    private final RedisTemplate<String, Object> redisTemplate;

    private final TenantContextHolder tenantContextHolder;

    @Override
    public Page<TenantPageVO> getTenantPage(TenantPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();

        // 查询数据
        Page<SysTenant> rolePage = this.page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<SysTenant>().and(StrUtil.isNotBlank(keywords), wrapper -> wrapper.like(StrUtil.isNotBlank(keywords), SysTenant::getName, keywords)));

        // 实体转换
        return tenantConverter.convertToPageVo(rolePage);
    }

    @Override
    public List<Option> listTenantOptions() {
        // 查询数据
        List<SysTenant> tenantList = this.list(new LambdaQueryWrapper<SysTenant>().select(SysTenant::getId, SysTenant::getName).orderByAsc(SysTenant::getCreateTime));
        // 实体转换
        return tenantConverter.entities2Options(tenantList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveTenant(TenantForm formData) {
        Long tenantId = formData.getId();

        // 编辑租户时，判断租户是否存在
        SysTenant oldTenant;
        if (tenantId != null) {
            oldTenant = this.getById(tenantId);
            Assert.isTrue(oldTenant != null, "租户不存在");
        }

        long count = this.count(new LambdaQueryWrapper<SysTenant>().ne(tenantId != null, SysTenant::getId, tenantId).and(wrapper -> wrapper.eq(SysTenant::getName, formData.getName())));
        Assert.isTrue(count == 0, "租户名称已存在，请修改后重试！");

        // 实体转换
        SysTenant systemTenant = tenantConverter.convertToEntity(formData);
        this.saveOrUpdate(systemTenant);

        // todo 创建默认角色

        // todo 创建默认菜单

        // todo 关联默认角色和默认菜单的关系

        // todo 创建默认用户
        return systemTenant.getId();
    }

    @Override
    public Long updateTenant(Long deptId, TenantForm formData) {
        // 校验部门名称/部门编号是否存在
        long count = this.count(new LambdaQueryWrapper<SysTenant>().ne(SysTenant::getId, deptId).eq(SysTenant::getName, formData.getName()));
        Assert.isTrue(count == 0, "租户名称已存在");
        // form->entity
        SysTenant entity = tenantConverter.convertToEntity(formData);
        entity.setId(deptId);

        // 保存部门并返回部门ID
        boolean result = this.updateById(entity);
        Assert.isTrue(result, "租户更新失败");

        return entity.getId();
    }

    @Override
    public boolean deleteByIds(String ids) {
        if (StrUtil.isNotBlank(ids)) {
            String[] tenantIds = ids.split(",");
            this.removeByIds(Arrays.asList(tenantIds));
        }
        return true;
    }

    @Override
    public TenantForm getTenantForm(Long id) {
        // 获取字典
        SysTenant entity = this.getById(id);
        Assert.isTrue(entity != null, "租户不存在");
        return tenantConverter.convertToForm(entity);
    }

    @Override
    public boolean switchTenant(Long tenantId) {
        tenantContextHolder.setTenant(tenantId);
        return true;
    }
}
